package com.klun.concDesign.chapterThree;


import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * 简单的展示 Fork/Join 框架的使用   计算求和数列
 *  注意： 函数的调用层次很深，有可能导致栈内存溢出 stackoverflowerror
 */
public class CountTask extends RecursiveTask<Long>{
    private static final int THRESHOLD = 1000;
    private long start;
    private long end;

    public CountTask(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long sum = 0;
        boolean canCompute = (end - start) < THRESHOLD;
        if (canCompute){
            for (long i = start; i <= end; i++) {
                sum += i;
            }
        }else {
            // 分为100 个小任务
            long step = (end + start )/100;
           ArrayList<CountTask> subTasks = new ArrayList<>();
            long pos = start;
            for (int i = 0; i < 100; i++) {
                long lastOne  = pos + step;
                if(lastOne > end) lastOne = end;
                CountTask subTask = new CountTask(pos,lastOne);
                pos+=step+1;
                subTasks.add(subTask);
                // 用fork 提交子任务
                subTask.fork();
            }
            for(CountTask t : subTasks){
                sum+=t.join();
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        CountTask countTask = new CountTask(0, 1000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(countTask);
        try{
            long l = System.currentTimeMillis();
            Long res = submit.get();
            long l1 = System.currentTimeMillis();
            System.out.println(res+"执行时间："+(l1-l));
            long sum = 0;
            for (long i = 0; i <= 1000; i++) {
                sum += i;
            }
            long l2 = System.currentTimeMillis();
            System.out.println(sum+"执行时间："+(l2-l1));
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

}
